package com.leff.cards.data;

import java.util.ArrayList;

import org.json.simple.JSONArray;

import com.leff.cards.util.Secrets;
import com.leff.cards.util.Dictionary;

public class Group extends BaseGroup implements Secrets {
	
	public QueryCard activeCard;
	public ArrayList<AbstractCard> responseCards;
	public ArrayList<HistoryItem> history;
	
	public boolean isVoter;
	public boolean readyForVote;
	public boolean hasSubmitted;
	
	public String voterName;

	public Group() {
	}
	
	public static Group fromDictionary(Dictionary dict) {
		
		Group G = new Group();
		
		G.id = (Long)dict.get("id");
		G.name = (String)dict.get("name");

		G.isVoter = (Boolean)dict.get("isVoter");
		if(G.isVoter) {
			G.readyForVote = (Boolean)dict.get("readyForVote");
		} else {
			G.hasSubmitted = (Boolean)dict.get("hasSubmitted");
			G.voterName = (String)dict.get("voter");
		}
		
		Dictionary activeCard = Dictionary.fromJSONObject(dict.get("active_card"));
		G.activeCard = QueryCard.fromDictionary(activeCard);
		
		G.responseCards = new ArrayList<AbstractCard>();
		JSONArray responseCards = (JSONArray)dict.get("cards");
		for(Object O : responseCards) {
			if(G.isVoter) {
				G.responseCards.add(CompositeResponseCard.fromJSONArray((JSONArray)O));
			} else {
				Dictionary cardDict = Dictionary.fromJSONObject(O);
				G.responseCards.add(ResponseCard.fromDictionary(cardDict));
			}
		}
		
		G.history = new ArrayList<HistoryItem>();
		JSONArray history = (JSONArray)dict.get("history");
		for(Object O : history) {
			Dictionary histDict = Dictionary.fromJSONObject(O);
			G.history.add(HistoryItem.fromDictionary(histDict));
		}

		G.members = new ArrayList<User>();
		JSONArray usersArr = (JSONArray)dict.get("members");
		for(Object O : usersArr) {
			Dictionary user = Dictionary.fromJSONObject(O);
			G.members.add(User.fromDictionary(user));
		}
		
		return G;
	}
}
